package dbexp.filter;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * @author Michał Skrzyński
 * @email michal_skrzynski@o2.pl
 */
public class GzipResponseWrapper extends HttpServletResponseWrapper {
	private GzipOS gzipOut = null;

	private PrintWriter pw = null;

	public GzipResponseWrapper(HttpServletResponse hsr) {
		super(hsr);
	}

	public GZIPOutputStream getGZIPOutputStream() {
		return this.gzipOut.instance;
	}

	private Object usedStream = null;

	public ServletOutputStream getOutputStream() throws IOException {
		if ((usedStream != null) && (usedStream != pw)) {
			throw new IllegalStateException();
		}

		if (gzipOut == null) {
			gzipOut = new GzipOS(getResponse().getOutputStream());
			usedStream = gzipOut;
		}
		return gzipOut;
	}

	public PrintWriter getWriter() throws IOException {
		if ((usedStream != null) && (usedStream != gzipOut)) {
			throw new IllegalStateException();
		}
		if (pw == null) {
			gzipOut = new GzipOS(getResponse().getOutputStream());
			OutputStreamWriter osw = new OutputStreamWriter(gzipOut,
					getResponse().getCharacterEncoding());
			pw = new PrintWriter(osw);
			usedStream = pw;
		}
		return pw;
	}
}
